package org.jeecg.modules.app.utils;


import io.jsonwebtoken.*;

import org.jeecg.modules.app.entity.Customer;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author 李圳川
 * @version 1.0
 * @date 2022/1/27 20:56
 * @content
 */
@Component
public class JwtUtil {

    // 一天
    //private  static final long time = 1000 * 60 * 60 * 24;

    //两个个小时失效
    private  static final long time = 1000 * 60 * 60 * 2;

    private static final String signature = "1a2b3d4c";


    public static String jwt(Customer customer) {
        JwtBuilder jwtBuilder = Jwts.builder();
        String jwtToken = jwtBuilder
                //hearder
                .setHeaderParam("typ", "JWT")
                .setHeaderParam("alg", "HS256")
                .setSubject("student-login")
                .setExpiration(new Date(System.currentTimeMillis() + time))
                .setId(customer.getId())
                //signature
                .signWith(SignatureAlgorithm.HS256, signature)
                .compact();
        return jwtToken;
    }

    public  static String  parse(String token) {
        JwtParser jwtParser = Jwts.parser();
        jwtParser.setSigningKey(signature).parseClaimsJws(token);
        Jws<Claims> claimsJws = jwtParser.setSigningKey(signature).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return claims.getId();
    }

    public  static Boolean checkToken(String token){
        if(token == null){
            return false;
        }
        try{
            Jwts.parser().setSigningKey(signature).parseClaimsJws(token);
            return true;
        }catch (Exception e){
            return false;
        }
    }
}
